﻿# -*- coding:utf-8  -*-

import hmac
import hashlib
import base64
import uuid
import requests
import time
import json

class API2Request:
    """
    本类是对 Virbox LM OpenAPI V2 的请求方式进行简单封装，仅用于向开发者展示 OpenAPI 的使用方法，
    不应应用于生产环境
    """
    def __init__(self, appUrl, appId, appSecret):
        self._appUrl = appUrl
        self._appId = appId
        self._appSecret = appSecret

    def _makeSignature(self, resurl, requestbody, timestampe, nonce):
        """
        签名，同时将签名结果进行 base64  编码
        :param resUrl:       资源地址
        :param requestBody:  请求体
        :param timeStampe:   时间戳 long
        :param nonce:        随机数uuid
        :return:
        """
        return base64.b64encode(hmac.new(self._appSecret,
                                         bytes(timestampe+nonce+resurl+requestbody),hashlib.sha256)
                                .digest())

    def _buildRequest(self, requestjson, requesturl):
        """
        构建请求，包括设置各个header头和设置请求地址
        :param requestjson:
        :param requesturl:
        :return: 响应字符串
        """

        requestjson=json.dumps(requestjson,encoding='utf-8',separators=(",",":"))
        # 填充自定义的请求头
        headers = dict()
        headers["Content-type"] = "application/json"
        headers["SenseAppID"] = self._appId
        # 填充时间戳
        headers["SenseTimestamp"] = str(long(time.time()*1000))
        # 填充随机数
        headers["SenseNonce"] = str(uuid.uuid4())
        # 填充数据签名
        headers["SenseSign"] = self._makeSignature(resurl=requesturl,
                                                   requestbody=requestjson,
                                                   timestampe=headers["SenseTimestamp"],
                                                   nonce=headers["SenseNonce"])

        response = requests.post(url=self._appUrl+requesturl, headers=headers, data=requestjson)
        return response.text

    def send(self, requesturl, data):
        """
        发送请求
        requesturl 请求地址
        data       请求数据, dict 类型
        """
        result = self._buildRequest(requesturl=requesturl, requestjson=data)
        print result
        return json.loads(result)
